﻿using System;
using System.Threading;
using Microsoft.Phone.Controls;

namespace WP7AppLifecycleServiceApp
{
    /// <summary>
    /// Class for the Main page in the application. 
    /// </summary>
    public partial class MainPage : PhoneApplicationPage, WP7AppLifecycleService.IPageStateHandler, WP7AppLifecycleService.IPhoneLockedHandler
    {
        #region Fields

        /// <summary>
        /// Holds whether the phone lock handler has been already initialized.
        /// </summary>
        private bool registeredPhoneLockedHandler = false;

        /// <summary>
        /// Holds the date time when the lock of the phone started.
        /// </summary>
        private DateTime startTime;

        #endregion Fields

        #region Constructor
        
        /// <summary>
        /// Initializes a new instance of the <see cref="MainPage"/> class.
        /// </summary>
        public MainPage()
        {
            ViewModel vm = new ViewModel();
            InitializeComponent();
            WP7AppLifecycleService.WP7AppLifecycleApplicationService.Current.RegisterApplicationStateHandler(this, vm);
            WP7AppLifecycleService.WP7AppLifecycleApplicationService.Current.RegisterPageStateHandler(this, this);
            this.phoneLockedButton.Click += this.OnPhoneLockedClick;
            this.DataContext = vm;
        }

        #endregion Constructor

        #region interface IPageStateHandler

        /// <summary>
        /// Saves the page state when the application is tombstoned.
        /// </summary>
        /// <param name="state">A <see cref="System.Collections.Generic.IDictionary{String, Object}"/> instance
        /// that can be used to store the page state.</param>
        /// <remarks>It would be desirable to be able to use PhoneApplicationPage.State in the implementation
        /// of methods, but due to implementation details when data needs to be restored it won´t be available.
        /// </remarks>
        public void SavePageState(System.Collections.Generic.IDictionary<string, object> state)
        {
            if (null == state)
            {
                throw new ArgumentNullException("state");
            }

            state["MainPage.selectedItem"] = listBox.SelectedItem;
        }

        /// <summary>
        /// Restores the data of the page when the application comes back to life
        /// after having been tombstoned.
        /// </summary>
        /// <param name="state">A <see cref="System.Collections.Generic.IDictionary{String, Object}"/> instance
        /// that can be used to restore the page state.</param>
        /// <remarks>PhoneApplicationPage.State is not available.</remarks>
        public void RestorePageState(System.Collections.Generic.IDictionary<string, object> state)
        {
            if (null == state)
            {
                throw new ArgumentNullException("state");
            }

            if (state.ContainsKey("MainPage.selectedItem"))
            {
                listBox.SelectedItem = state["MainPage.selectedItem"];
            }
        }

        /// <summary>
        /// Deletes any state saved when the application was tombstoned. 
        /// <para>This method will automatically be called right after RestoreApplicationState is
        /// successfully executed.</para>
        /// </summary>
        /// <param name="state">A <see cref="System.Collections.Generic.IDictionary{String, Object}"/> instance
        /// that can be used to store the page state.</param>
        /// <remarks>PhoneApplicationPage.State is not available.</remarks>
        public void DeletePageState(System.Collections.Generic.IDictionary<string, object> state)
        {
            if (null == state)
            {
                throw new ArgumentNullException("state");
            }

            if (state.ContainsKey("MainPage.selectedItem"))
            {
                state.Remove("MainPage.selectedItem");
            }
        }

        #endregion interface IPageStateHandler

        #region interface IPhoneLockedHandler

        /// <summary>
        /// The phone has been locked
        /// </summary>
        public void Locked()
        {
            this.startTime = DateTime.Now;
        }

        /// <summary>
        /// The phone has been unlocked
        /// </summary>
        public void Unlocked()
        {
            TimeSpan totalTime = DateTime.Now - this.startTime;

            System.Windows.MessageBox.Show("Total number of seconds locked = " + totalTime.TotalSeconds.ToString(System.Globalization.CultureInfo.InvariantCulture));
        }

        #endregion interface IPhoneLockedHandler

        /// <summary>
        /// Called when the "Phone Locked" Button is clicked. 
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">A <see cref="RoutedEventArgs"/> instance with the event data.</param>
        private void OnPhoneLockedClick(object sender, System.Windows.RoutedEventArgs e)
        {
            if (!this.registeredPhoneLockedHandler)
            {
                WP7AppLifecycleService.WP7AppLifecycleApplicationService.Current.RegisterPhoneLockedHandler(this);
            }
            else
            {
                WP7AppLifecycleService.WP7AppLifecycleApplicationService.Current.UnregisterPhoneLockedHandler(this);
            }

            this.registeredPhoneLockedHandler = !this.registeredPhoneLockedHandler;
        }
    }
}